using System.Web.Mvc;
using AgileBoard.Core;
using SharpArch.Core.PersistenceSupport;
using SharpArch.Core.DomainModel;
using System.Collections.Generic;
using System;
using SharpArch.Web.NHibernate;
using NHibernate.Validator.Engine;
using System.Text;
using SharpArch.Web.CommonValidator;
using SharpArch.Core;

namespace AgileBoard.Web.Controllers
{
    [HandleError]
    public class StatesController : Controller
    {
        public StatesController(IRepository<State> stateRepository) {
            Check.Require(stateRepository != null, "stateRepository may not be null");

            this.stateRepository = stateRepository;
        }

        [Transaction]
        public ActionResult Index() {
            IList<State> states = stateRepository.GetAll();
            return View(states);
        }

        [Transaction]
        public ActionResult Show(int id) {
            State state = stateRepository.Get(id);
            return View(state);
        }

        public ActionResult Create() {
            StateFormViewModel viewModel = StateFormViewModel.CreateStateFormViewModel();
            return View(viewModel);
        }

        [ValidateAntiForgeryToken]
        [Transaction]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(State state) {
            if (ViewData.ModelState.IsValid && state.IsValid()) {
                stateRepository.SaveOrUpdate(state);

                TempData[ControllerEnums.GlobalViewDataProperty.PageMessage.ToString()] = 
					"The state was successfully created.";
                return RedirectToAction("Index");
            }

            StateFormViewModel viewModel = StateFormViewModel.CreateStateFormViewModel();
            viewModel.State = state;
            return View(viewModel);
        }

        [Transaction]
        public ActionResult Edit(int id) {
            StateFormViewModel viewModel = StateFormViewModel.CreateStateFormViewModel();
            viewModel.State = stateRepository.Get(id);
            return View(viewModel);
        }

        [ValidateAntiForgeryToken]
        [Transaction]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(State state) {
            State stateToUpdate = stateRepository.Get(state.Id);
            TransferFormValuesTo(stateToUpdate, state);

            if (ViewData.ModelState.IsValid && state.IsValid()) {
                TempData[ControllerEnums.GlobalViewDataProperty.PageMessage.ToString()] = 
					"The state was successfully updated.";
                return RedirectToAction("Index");
            }
            else {
                stateRepository.DbContext.RollbackTransaction();

				StateFormViewModel viewModel = StateFormViewModel.CreateStateFormViewModel();
				viewModel.State = state;
				return View(viewModel);
            }
        }

        private void TransferFormValuesTo(State stateToUpdate, State stateFromForm) {
			stateToUpdate.Label = stateFromForm.Label;
			stateToUpdate.OrderIndex = stateFromForm.OrderIndex;
			stateToUpdate.Stories = stateFromForm.Stories;
        }

        [ValidateAntiForgeryToken]
        [Transaction]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Delete(int id) {
            string resultMessage = "The state was successfully deleted.";
            State stateToDelete = stateRepository.Get(id);

            if (stateToDelete != null) {
                stateRepository.Delete(stateToDelete);

                try {
                    stateRepository.DbContext.CommitChanges();
                }
                catch {
                    resultMessage = "A problem was encountered preventing the state from being deleted. " +
						"Another item likely depends on this state.";
                    stateRepository.DbContext.RollbackTransaction();
                }
            }
            else {
                resultMessage = "The state could not be found for deletion. It may already have been deleted.";
            }

            TempData[ControllerEnums.GlobalViewDataProperty.PageMessage.ToString()] = resultMessage;
            return RedirectToAction("Index");
        }

		/// <summary>
		/// Holds data to be passed to the State form for creates and edits
		/// </summary>
        public class StateFormViewModel
        {
            private StateFormViewModel() { }

			/// <summary>
			/// Creation method for creating the view model. Services may be passed to the creation 
			/// method to instantiate items such as lists for drop down boxes.
			/// </summary>
            public static StateFormViewModel CreateStateFormViewModel() {
                StateFormViewModel viewModel = new StateFormViewModel();
                
                return viewModel;
            }

            public State State { get; internal set; }
        }

        private readonly IRepository<State> stateRepository;
    }
}
